//
//  UIButton+BOCNetworkImage.m
//  BOCImageTools
//
//  Created by LeungChaos on 16/5/11.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "UIButton+BOCNetworkImage.h"
#import "BOCNetworkImageManager.h"
#import "BOCImageDownloadTask.h"

NSString * buttonImageDownloadTaskKey(UIControlState state){
    return [NSString stringWithFormat:@"BOCButtonImageDownloadTaskKey__forState%lu",(unsigned long)state];
}

@implementation UIButton (BOCNetworkImage)

/******** setImage  *********/
- (void)setNetworkImageForState:(UIControlState)state withURL:(NSURL *)url
{
    [self setNetworkImageForState:state withURL:url completion:nil];
}

- (void)setNetworkImageForState:(UIControlState)state withURL:(NSURL *)url completion:(DownloadCompletionBlock)completionBlock
{
    [self setNetworkImageForState:state withURL:url placeholderImage:nil completion:completionBlock];
}

- (void)setNetworkImageForState:(UIControlState)state withURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage completion:(DownloadCompletionBlock)completionBlock
{
    [self setNetworkImageForState:state withURL:url placeholderImage:placeholderImage progress:nil completion:completionBlock];
}

- (void)setNetworkImageForState:(UIControlState)state withURL:(NSURL *)url progress:(BOCProgressHandlerProgressBlock)progressBlock completion:(DownloadCompletionBlock)completionBlock
{
    [self setNetworkImageForState:state withURL:url placeholderImage:nil progress:progressBlock completion:completionBlock];
}

- (void)setNetworkImageForState:(UIControlState)state withURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage progress:(BOCProgressHandlerProgressBlock)progressBlock completion:(DownloadCompletionBlock)completionBlock
{
    [self downloadImageIsBackgroundImage:false ForState:state withURL:url placeholderImage:placeholderImage progress:progressBlock completion:completionBlock];
}

/******** setBackgroundImage  *********/

- (void)setNetworkBackgroundImageForState:(UIControlState)state withURL:(NSURL *)url
{
    [self setNetworkBackgroundImageForState:state withURL:url completion:nil];
}

- (void)setNetworkBackgroundImageForState:(UIControlState)state withURL:(NSURL *)url completion:(DownloadCompletionBlock)completionBlock
{
    [self setNetworkBackgroundImageForState:state withURL:url placeholderImage:nil completion:completionBlock];
}

- (void)setNetworkBackgroundImageForState:(UIControlState)state withURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage completion:(DownloadCompletionBlock)completionBlock
{
    [self setNetworkBackgroundImageForState:state withURL:url placeholderImage:placeholderImage progress:nil completion:completionBlock];
}

- (void)setNetworkBackgroundImageForState:(UIControlState)state withURL:(NSURL *)url progress:(BOCProgressHandlerProgressBlock)progressBlock completion:(DownloadCompletionBlock)completionBlock
{
    [self setNetworkBackgroundImageForState:state withURL:url placeholderImage:nil progress:progressBlock completion:completionBlock];
}

- (void)setNetworkBackgroundImageForState:(UIControlState)state withURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage progress:(BOCProgressHandlerProgressBlock)progressBlock completion:(DownloadCompletionBlock)completionBlock
{
    [self downloadImageIsBackgroundImage:true ForState:state withURL:url placeholderImage:placeholderImage progress:progressBlock completion:completionBlock];
}

- (void)downloadImageIsBackgroundImage:(BOOL)isBackgroundImage
                              ForState:(UIControlState)state
                               withURL:(NSURL *)url
                      placeholderImage:(UIImage *)placeholderImage
                              progress:(BOCProgressHandlerProgressBlock)progressBlock
                            completion:(DownloadCompletionBlock)completionBlock
{
    [self cancelDownlaodTaskForState:state];
    dispatch_mainQueue_safely_sync(^{
        if (placeholderImage) {
            if (isBackgroundImage) {
                [self setBackgroundImage:placeholderImage forState:state];
            } else {
                [self setImage:placeholderImage forState:state];
            }
        } else {
            if (isBackgroundImage) {
                [self setBackgroundImage:[[UIImage alloc]init] forState:state];
            } else {
                [self setImage:[[UIImage alloc]init] forState:state];
            }
        }
    });
    
    BOCNetworkImageManager *manager = [BOCNetworkImageManager sharedManager];
    UIImage *cacheImage = [manager imageForURLkey:url];
    if (cacheImage) {
        dispatch_mainQueue_safely_sync(^{
            if (isBackgroundImage) {
                [self setBackgroundImage:cacheImage forState:state];
            } else {
                [self setImage:cacheImage forState:state];
            }
            if (completionBlock) {
                completionBlock(cacheImage, nil, nil);
            }
        });
    } else {
        __weak typeof(self) weakSelf = self;
        BOCImageDownloadTask *task =
        [manager downImageWithURL:url
                        progress:progressBlock
                          seccess:^(UIImage *image, NSURLResponse *response) {
                              
                              dispatch_mainQueue_safely_sync(^{
                                  if (isBackgroundImage) {
                                      [weakSelf setBackgroundImage:image forState:state];
                                  } else {
                                      [weakSelf setImage:image forState:state];
                                  }
                                  if (completionBlock) {
                                      completionBlock(image,response,nil);
                                  }
                              });
                          }
                             fail:^(NSError *error, NSURLResponse *response) {
                                 
                                 dispatch_mainQueue_safely_sync(^{
                                     if (completionBlock) {
                                         completionBlock(nil,response,error);
                                     }
                                 });
                             }
         ];
        if (task) {
            [self setDownloadTask:task forKey:buttonImageDownloadTaskKey(state)];
        }
        
    }
    
}

- (void)cancelDownlaodTaskForState:(UIControlState)state
{
    [self removeDownloadTaskForKey:buttonImageDownloadTaskKey(state)];
}


@end
